package com.qlogic.commons.platform.impls.ftp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import java.net.Socket;
import java.net.ServerSocket;


public class FTPDataSocket {

    /**
     *  The underlying socket for Active connection.
     */
    private ServerSocket activeSocket = null;

    /**
     *  The underlying socket for PASV connection or Socket accepted from server.
     */
    private Socket passiveSocket = null;

	/**
	 * Method FTPDataSocket.
	 * @param s
	 */
    /**
     *  Create socket wrapper for Active connection.
     */
    FTPDataSocket(ServerSocket s) {
         activeSocket = s;
    }

	/**
	 * Method FTPDataSocket.
	 * @param s
	 */
    /**
     *  Create socket wrapper for PASV connection.
     */
    FTPDataSocket(Socket s) {
         passiveSocket = s;
    }


	/**
	 * Method setTimeout.
	 * @param millis
	 * @throws IOException
	 */
    void setTimeout(int millis)
        throws IOException {

        if (passiveSocket != null)
            passiveSocket.setSoTimeout(millis);
        else if (activeSocket != null)
            activeSocket.setSoTimeout(millis);
    }


	/**
	 * Method getOutputStream.
	 * @return OutputStream
	 * @throws IOException
	 */
    OutputStream getOutputStream() throws IOException {

        if (passiveSocket != null) {
            return passiveSocket.getOutputStream();
        }
        else {
            // accept socket from server, in Active mode
            passiveSocket = activeSocket.accept();
            // get and return its OutputStream
            return passiveSocket.getOutputStream ();
        }
    }

	/**
	 * Method getInputStream.
	 * @return InputStream
	 * @throws IOException
	 */
    InputStream getInputStream() throws IOException {

        if (passiveSocket != null) {
            return passiveSocket.getInputStream();
        } else {
            // accept socket from server, in Active mode
            passiveSocket = activeSocket.accept();
            // get and return it's InputStream
            return passiveSocket.getInputStream ();
        }
    }

	/**
	 * Method close.
	 * @throws IOException
	 */
    void close() throws IOException {

        if (passiveSocket != null)
            passiveSocket.close();
        if (activeSocket != null)
            activeSocket.close();
    }
}
